package com.tourism.controller;

import com.tourism.common.Result;
import com.tourism.entity.LodgingInfo;
import com.tourism.service.LodgingInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/admin/lodging")
@CrossOrigin
public class LodgingInfoController {

    @Autowired
    private LodgingInfoService lodgingInfoService;

    // 使用相对路径，并指定在 resources 目录下
    private final String uploadPath = System.getProperty("user.dir") + "/src/main/resources/upload";


    @PostConstruct
    public void init() {
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        log.info("文件上传目录: {}", uploadPath);
    }

    @GetMapping("/{id}")
    public Result getLodgingById(@PathVariable Integer id) {
        return lodgingInfoService.getLodgingById(id);
    }

    @GetMapping("/list")
    public Result getLodgingList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name) {
        return lodgingInfoService.getLodgingList(page, pageSize, name);
    }

    @PostMapping("/add")
    public Result addLodging(@RequestBody LodgingInfo lodgingInfo) {
        return lodgingInfoService.addLodging(lodgingInfo);
    }

    @PutMapping("/update")
    public Result updateLodging(@RequestBody LodgingInfo lodgingInfo) {
        if (lodgingInfo.getId() == null) {
            return Result.fail("ID不能为空");
        }
        return lodgingInfoService.updateLodging(lodgingInfo);
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteLodging(@PathVariable Integer id) {
        return lodgingInfoService.deleteLodging(id);
    }

    @PostMapping("/batchDelete")
    public Result batchDeleteLodgings(@RequestBody List<Integer> ids) {
        return lodgingInfoService.batchDeleteLodgings(ids);
    }

    @GetMapping("/all")
    public Result getAllLodgings() {
        return lodgingInfoService.getAllLodgings();
    }

    @PostMapping("/upload")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.fail("上传文件不能为空");
            }

            long maxSize = 2 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                return Result.fail("文件大小不能超过2MB");
            }

            String contentType = file.getContentType();
            if (!isValidImageType(contentType)) {
                return Result.fail("只支持 JPG/PNG/WEBP 格式的图片");
            }

            String originalFilename = file.getOriginalFilename();
            String extension = getFileExtension(originalFilename);
            String newFileName = UUID.randomUUID().toString() + extension;

            File destFile = new File(uploadPath, newFileName);
            file.transferTo(destFile);
            // 返回文件名，前端拼接访问路径
            return Result.success("上传成功", newFileName);

        } catch (IOException e) {
            log.error("图片上传失败", e);
            return Result.fail("图片上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/image/{fileName}")
    public void getImage(@PathVariable String fileName, HttpServletResponse response) {
        File file = new File(uploadPath + File.separator + fileName);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        try {
            String contentType = getContentType(fileName);
            response.setContentType(contentType);
            response.setHeader("Cache-Control", "max-age=2592000");
            Files.copy(file.toPath(), response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("获取图片失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private boolean isValidImageType(String contentType) {
        if (contentType == null) return false;
        return contentType.equals("image/jpeg") ||
                contentType.equals("image/png") ||
                contentType.equals("image/webp");
    }

    private String getFileExtension(String fileName) {
        if (fileName == null) return ".jpg";
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex == -1) return ".jpg";
        return fileName.substring(lastDotIndex).toLowerCase();
    }

    private String getContentType(String fileName) {
        String extension = getFileExtension(fileName);
        switch (extension) {
            case ".jpg":
            case ".jpeg":
                return "image/jpeg";
            case ".png":
                return "image/png";
            case ".webp":
                return "image/webp";
            default:
                return "application/octet-stream";
        }
    }
}
